/**
 * 计算凸起按钮的信息
 */

import {
  ref,
  ComponentInternalInstance
} from "vue"
import {
  TabbarItem,
  TabbarProps
} from '../../../types/tn-tabbar'

type ItemRect = {
  width: number,
  left: number
}

export type BulgeButtonInfo = {
  left: number,
  width: number,
  itemIndex: number
}

export default function useBulgeButton(
  instance: ComponentInternalInstance,
  id: string
) {

  // 凸起按钮高度
  let bulgeHieght: number = 0
  // item列表
  let itemList: TabbarItem[] = []
  let rectInitCount: number = 0
  // tabbar容器信息
  let tabbarRectInfo: ItemRect = {
    width: 0,
    left: 0
  }
  // item容器信息
  let itemRectInfos: ItemRect[] = []
  // 凸起按钮位置信息
  let bulgeButtonInfo = ref<BulgeButtonInfo[]>([])

  // 更新用户设置信息
  const updateBulgeProps = (_props: TabbarProps) => {
    itemList = _props.data as TabbarItem[]
    bulgeHieght = Number(_props.bulgeHeight)
  }

  // 获取tabbarItem的容器信息
  const getTabbarItemRectInfo = () => {
    if (!itemList.length) return
    const query = uni.createSelectorQuery().in(instance)

    // 获取tabbar容器信息
    query.select(`#tn-tabbar-${id}`).boundingClientRect(() => {})

    for (let i = 0; i < itemList.length; i++) {
      if (itemList[i]?.bulge) {
        bulgeButtonInfo.value.push({
          width: 0,
          left: 0,
          itemIndex: i
        })
        query.select(`#tti-${id}_${i}`).boundingClientRect(() => {})
      }
      
    }
    query.exec((res: UniApp.NodeInfo[]) => {
      if (!res) {
        if (rectInitCount > 10) {
          return console.error('[tn-tabbar]初始化获取容器信息失败')
        }
        setTimeout(() => {
          getTabbarItemRectInfo()
          rectInitCount++
        }, 50)
        return
      }

      rectInitCount = 0
      const itemRect: UniApp.NodeInfo[] = res.slice(1, res.length)
      tabbarRectInfo.width = res[0].width || 0
      tabbarRectInfo.left = res[0].left || 0
      itemRectInfos = itemRect.map((item) => {
        return {
          width: item.width || 0,
          left: item.left || 0
        }
      })
      // console.log(itemRectInfos, tabbarRectInfo);
      _calcBulgeButtonRectInfo()
    })
  }

  // 计算凸起按钮的位置
  const _calcBulgeButtonRectInfo = () => {
    if (!itemRectInfos.length) return
    for (let i = 0; i < itemRectInfos.length; i++) {
      const item: ItemRect = itemRectInfos[i]
      let width: number = item.width - 20
      let left: number = item.left - tabbarRectInfo.left
      if (left < 0) left = 0
      // 计算居中位置
      left += (item.width - width) / 2
      bulgeButtonInfo.value[i].width = width
      bulgeButtonInfo.value[i].left = left
    }
    // console.log(bulgeButtonInfo);
  }

  return {
    bulgeButtonInfo,
    getTabbarItemRectInfo,
    updateBulgeProps
  }
}